<!-- modelInstance的公共组件：增删改查; -->
<template>
  <starGenView :title="title">
    <cfg-table v-if="!!this.collectionObject"
      ref="table"
      :columns="columns"
      :data="collectionObject.records"
      :loading="loading"
      :config="tableConfig"
      :pageSizeOpts="pageSizeOpts"
      :pageNavigation="pageNavigation"
      :queryFormItem="queryFormItem"
      :collapseFormItem="collapseFormItem"
      :additionalAction="additionalAction"
      @loadPage="loadPage"
      @handleClick="(row, index) => $emit('handleClick', row, index)"
      @handleDbClick="(row, index) => $emit('handleDbClick', row, index)"
      @handleSelect="(selection, row) => $emit('handleSelect', selection, row)"
      @handleSelectCancel="(selection, row) => $emit('handleSelectCancel', selection, row)"
      @handleCreate="handleCreate"
      @handleDetail="handleDetail"
      @handleEdit="handleEdit"
      @handleDelete="handleDelete"
      @handleDeleteMultiple="handleDeleteMultiple"
      @handleSearch="handleSearch"
      @handleReset="handleReset"
    />
    <cfgCrudAddModal v-show="modelDrawer.status==='new'"
      v-bind="modalConfig"
      :isInstance="true"
      :classObject="classObject"
      :collectionObject="collectionObject"
      :modelList="modelList"
      :drawer="modelDrawer"
      :fields="modalFormItem"
      @submit="handleNewAddSubmit"
    />
    <cfgCrudModal v-show="modelDrawer.status!=='new'"
      v-bind="modalConfig"
      :isInstance="true"
      :classObject="classObject"
      :collectionObject="collectionObject"
      :modelList="modelList"
      :drawer="modelDrawer"
      :fields="modalFormItem"
      @submit="handleEditSubmit"
    />
    <cfgModalHier
      :isInstance="true"
      v-bind="modalConfig"
      :classObject="classObject"
      :collectionObject="collectionObject"
      :modelList="modelList"
      :drawer="registerDrawer"
      @submit="handleEditSubmit"
      @nodeSelect="data => $emit('nodeSelect', data)"
    />
  </starGenView>
</template>

<script>
import cfgCrudModal from 'public/components/configComp/basic/cfgCrud/cfgCrud-modal'
import cfgCrudAddModal from 'public/components/configComp/basic/cfgCrud/cfgCrud-AddModal'
import util from '../util'

export default {
  name: 'modelDesign_model',
  components: { cfgCrudAddModal, cfgCrudModal },
  data() {
    let data = this.tools.lodash.merge({
      modelName: this.prefix,
      modelFilter: '',
      deleteById: true,
      classObject: null,
      collectionObject: null,
      modelList: [],
      loading: false,
      modalNeedQuery: true,
      pageSizeOpts: [10, 30, 50, 100],
      pageNavigation: { total: 0, pageSize: 100, pageNumber: 1 },
      modalConfig: {
        isInstance: true,
        hasFeatures: true,
        labelWidth: 90,
      },
      modelDrawer: {
        status: 'new',
        show: false
      },
      registerDrawer: {
        show: false
      },
      tableConfig: {
        search: true,
        addButton: true,
        actionEdit: true,        // 显示编辑按钮, 默认为true
        actionDetail: true,      // 显示查看按钮, 默认为true
        actionDelete: true,      // 显示删除按钮, 默认为true
        batchDeleteButton: true, // 显示批量删除按钮
        downloadIcon: true,
        uploadIcon: true,
        uploadUrl: '/',
        tableSizeIcon: true,
        fullscreenIcon: true,
        refreshIcon: true,
        columnSettingIcon: true,
        action: true,
        actionOption: {},
        actionButtons: [],   // action追加的button
        additionalAction: {  // 附加操作的配置，以及button列表
          show: true,
          width: 100,
          buttons: [
            {
              title: { 'zh-CN': '注册', 'en-US': 'register' }, color: 'green',
              eventName: 'actionRegister'
            }
          ]
        }
      },
    }, this.config)
    return data
  },
  methods:{
    async loadPage(pageNavigation, filter = {}) {
      filter = this.isReset ? filter : {...filter, ...this.searchData}
      if (this.isPointer) {
        delete filter.nodeId
      }

      let condition=this.collectionObject.util.getFilter(filter, 'like')

      if (this.modelFilter) {
        condition += (condition ? ' and ' : '') + this.modelFilter
      }
      this.loading = true;
      let flag = await this.collectionObject.queryInfoByPage(pageNavigation.pageNumber, pageNavigation.pageSize, condition)

      if (flag) {
        this.pageNavigation.total = this.collectionObject.total;
        // this.dataChange('query')
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleSearch(filter) {
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation, filter)
    },
    handleReset() {
      this.isReset = true
      this.pageNavigation.pageNumber = 1;
      this.loadPage(this.pageNavigation)
    },
    async actionRegister(row, index) {
      let filter = {id: row.id}
      this.loading = true;
      this.registerDrawer.status = 'edit'

      if (!this.modalNeedQuery) {
        this.classObject.setRecord(row)
        this.registerDrawer.show = true
        this.loading = false
      }
      else if (await this.getRecord(filter)) {
        this.registerDrawer.show = true
        this.loading = false
      } else {
        this.loading = false
      }
    },
    async getRecord(filter) {
      let flag = await this.classObject.query(this.collectionObject.util.getFilter(filter))
      return flag
    },
    async deleteRecord(classNames) {
      this.loading = true;
      let flag= await this.collectionObject.deleteByClassNames(classNames)

      this.clearTableSelection(flag)
      this.dataChange('delete')
      this.loading = false;
      return flag
    },
    async handleNewAddSubmit() {
      this.loading = true;
      if (await this.classObject.add()) {
        this.collectionObject.addRecord(this.classObject.record);
        this.dataChange('add')
        this.loading = false;
        this.modelDrawer.show = false
        return true
      } else {
        this.loading = false;
        return false
      }
    },
    async handleEditSubmit() {
      this.loading = true;
      let flag = await this.classObject.updateById()
      if (flag) {
        this.collectionObject.updateRecord(this.classObject.record)
        this.dataChange('edit')
        this.loading = false;
        this.modelDrawer.show = false
        this.registerDrawer.show = false
      } else {
        this.loading = false;
      }
    },
    handleCreate() {
      this.classObject.setRecord()
      this.type && (this.classObject.record.type = this.type)
      this.modelDrawer.status = 'new'
      this.modelDrawer.show = true
    },
    async handleEdit(row, index) {
      let filter = {id: row.id}
      if (this.tableConfig.editBtnAction) {
        this[this.tableConfig.editBtnAction](row, index)
        return
      }
      this.loading = true;
      this.modelDrawer.status = 'edit'

      if (!this.modalNeedQuery) {
        this.classObject.setRecord(row)
        this.modelDrawer.show = true
        this.loading = false
      } else if (await this.getRecord(filter)) {
        this.modelDrawer.show = true
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    async handleDetail(row, index) {
      let filter = {id: row.id}
      this.loading = true;
      this.modelDrawer.status = 'read'

      if (!this.modalNeedQuery) {
        this.classObject.setRecord(row)
        this.modelDrawer.show = true
        this.loading = false
      }
      else if (await this.getRecord(filter)) {
        this.modelDrawer.show = true
        this.loading = false;
      } else {
        this.loading = false;
      }
    },
    handleDelete(row, index) {
      if (this.deleteById) {
        this.deleteRecordById([row.id])
      } else {
        this.deleteRecordByInstanceId([row.instanceId])
      }
    },
    async handleDeleteMultiple(selection) {
      if (this.deleteById) {
        await this.deleteRecordById(selection.map(item => item.id))
      } else {
        await this.deleteRecordByInstanceId(selection.map(item => item.instanceId))
      }
    },
    async deleteRecordById(ids) {
      this.loading = true;
      let flag = await this.collectionObject.deleteByIds(ids)

      this.clearTableSelection(flag)
      this.dataChange('delete')
      this.loading = false;
      return flag
    },
    async deleteRecordByInstanceId(instanceIds) {
      this.loading = true;
      let flag = await this.collectionObject.deleteByInstanceIds(instanceIds)

      this.clearTableSelection(flag)
      this.dataChange('delete')
      this.loading = false;
      return flag
    },
    clearTableSelection(flag) {
      flag && (this.$refs.table.selection = [])
    },
    dataChange(type) {
      this.$emit('dataChange', type)
    },
    // 实例页面，获取对应的model列表
    // getModelList() {
    //   let api = this.$api[this.modelName[0].toLocaleUpperCase() + this.modelName.slice(1) + 'Configuration']
    //   api = typeof api === 'function' ? api() : api;

    //   api.query({condition: this.type ? `type like '${this.type}%'` : ''}).then(res => {
    //     this.modelList = res
    //   })
    // },
  },
  created() {
    this.collectionObject = this.$modelObject.create(`${this.modelName}Collection`);
    this.classObject = this.$modelObject.create(this.modelName)
    // 实例页面，获取对应的model列表
    this.collectionModelObject = this.$modelObject.create(`${this.modelName}ModelCollection`)
    this.modelFilter = util.getModelFilter.call(this, this.collectionModelObject)
    this.collectionModelObject.query(this.modelFilter).then(flag => {
      this.modelList = this.collectionModelObject.records
    })
  },
  beforeMount() {
    this.loadPage(this.pageNavigation)
    // this.getModelList()
  },
  computed: {
    modalFormItem() {
        return [
            {
                key: 'type',
                title: { 'zh-CN': '所属类型', 'en-US': 'model type' }[this.G_Locale],
                config: {
                  // type: 'select',
                  // disabled: !!this.type,
                  // options: this.typeList,
                  // clearable: true,
                  type: this.type ? 'text' : 'select',
                  options: this.tools.lodash.uniq(this.modelList.map(item => ({
                    label: item.type, value: item.type
                  }))),
                  readonly: !!this.type,
                },
                editConfig: {disabled: true},
                rules: { required: true, trigger: 'blur', 
                    message: { 'zh-CN': '模板类型不能为空', 'en-US': 'The model type cannot be empty' }[this.G_Locale] 
                }
            },
            {
                key: 'className',
                title: {
                    'zh-CN': '模型类名',
                    'en-US': 'class name'
                }[this.G_Locale],
                config: { type: 'select', maxlength: 50, clearable: true, options: [] },
                editConfig: {disabled: true},
                rules: { required: true, trigger: 'blur', 
                    message: { 'zh-CN': '模型类名不能为空', 'en-US': 'The class name cannot be empty' }[this.G_Locale] 
                }
            },
            {
                key: 'name',
                title: {
                    'zh-CN': '实例名',
                    'en-US': 'instance name'
                }[this.G_Locale],
                span: 24,
                config: {
                    type: 'text',
                    clearable: true,
                    placeholder: {
                        'zh-CN': '请输入实例名',
                        'en-US': 'please input instance name'
                    }[this.G_Locale],
                },
                rules: { required: true, trigger: 'blur', 
                    message: { 'zh-CN': '实例名不能为空', 'en-US': 'The instance name cannot be empty' }[this.G_Locale] 
                }
            },
            {
                key: 'comments',
                title: {
                    'zh-CN': '说明',
                    'en-US': 'comments'
                }[this.G_Locale],
                span: 24,
                config: {
                    type: 'textarea',
                    autosize: {minRows: 1, maxRows: 5},
                    clearable: true,
                    placeholder: {
                        'zh-CN': '请输入说明',
                        'en-US': 'please input comments'
                    }[this.G_Locale],
                }
            },
        ]
    },
    queryFormItem() {
        return [
            {
              key: 'type',
              title: {
                'zh-CN': '所属类型',
                'en-US': 'type'
              }[this.G_Locale],
              config: {
                type: 'text',
                // options: this.typeList,
                clearable: true,
              }
            },
            {
                key: 'className',
                title: {
                    'zh-CN': '模型类名',
                    'en-US': 'class name'
                }[this.G_Locale],
                config: {
                    type: 'text',
                    clearable: true,
                }
            },
            {
                key: 'name',
                title: {
                    'zh-CN': '实例名',
                    'en-US': 'instance name'
                }[this.G_Locale],
                config: {
                    type: 'text',
                    clearable: true,
                }
            },
        ]
    },
    columns() {
        let res = [
            {
                key: 'type',
                title: {
                    'zh-CN': '所属类型',
                    'en-US': 'type'
                }[this.G_Locale],
                minWidth: 100,
                align: 'center',
                show: true
            },
            {
                key: 'className',
                title: {
                    'zh-CN': '模型类名',
                    'en-US': 'class name'
                }[this.G_Locale],
                minWidth: 100,
                align: 'center',
                show: true
            },
            {
                key: 'name',
                title: {
                    'zh-CN': '实例名',
                    'en-US': 'instance name'
                }[this.G_Locale],
                minWidth: 100,
                align: 'center',
                show: true
            },
            {
                key: 'version',
                title: {
                    'zh-CN': '版本号',
                    'en-US': 'version'
                }[this.G_Locale],
                minWidth: 100,
                align: 'center',
                show: true,
            },
            {
                key: 'published',
                title: {
                    'zh-CN': '是否发布',
                    'en-US': 'published'
                }[this.G_Locale],
                minWidth: 100,
                align: 'center',
                show: true
            },
            {
                key: 'createTime',
                title: {
                    'zh-CN': '创建时间',
                    'en-US': 'create time'
                }[this.G_Locale],
                minWidth: 112,
                align: 'center',
                show: true,
            },
            {
                key: 'updateTime',
                title: {
                    'zh-CN': '更新时间',
                    'en-US': 'update time'
                }[this.G_Locale],
                minWidth: 112,
                align: 'center',
                show: true,
            },
        ]
        return this.computedConfig.columns || res
    },
    collapseFormItem() {
      return this.queryFormItem
    },
    lang() {
      return {
        "en-US": {
          type: 'type',
          className: 'class name',
          instanceName: 'instance name',
          category: 'category',
          eventName: 'event name',
          comments: 'comments',
          version:'version',
          published:'published',
          createTime:'createTime',
          updateTime:'updateTime'
        },
        "zh-CN": {
          type: '所属类型',
          className: '模型类名',
          instanceName: '实例名',
          category: '分类',
          eventName: '事件名称',
          comments:'注释',
          version:'版本',
          published:'已发布',
          createTime:'创建时间',
          updateTime:'更新时间'
        },
      }[this.G_Locale]
    },
    typeList() {
        return this.$modelObject.getModelType(this.modelName.replace('Model', ''), this.type);
    },
    additionalAction() {
      let buttons = []
      let action = this.tableConfig.additionalAction;

      if (!action || !action.show || !action.buttons || !action.buttons.length) {
        return { show: false }
      }

      action.buttons.forEach(item => {
        item.title = item.title[this.G_Locale]
        item.event = (row, index) => {
          let res = ''
          if (item.eventName && this[item.eventName]) {
            res = this[item.eventName](row, index)
          }
          if (item.triggerName) {
            res = this.$emit(item.triggerName, item, row, index)
          }
          return res;
        }
        buttons.push(item)
      })

      return {
        key: 'additionalAction',
        title: { 'zh-CN': '附加操作', 'en-US': 'addition action' }[this.G_Locale],
        slot: 'additionalAction',
        width: 280,
        fixed: 'right',
        align: 'center',
        ...action,
        buttons
      }
    },
  },
  props:{
    title:{
      type:String
    },
    type:{
      type:String
    },
    prefix:{
      type:String
    },
    config: {
      default() {
        return {}
      }
    },
    computedConfig: {
      default() {
        return {}
      }
    },
    isPointer: {
      type: Boolean
    },
    defaultType: {
      default: ''
    }
  },
}
</script>
